import React, { useEffect, useRef } from 'react'
import config from '../common/Common'
import '@/style/sider/fileItem.scss'
import { Input } from 'antd';
import useKeyPress from 'hooks/useKeyPress';
const basePadding = 20;

export default function FileFloder({ padding, file, onFileClick, updateFIleName, editID, setEditID }) {
    const { IconFont } = config
    const enterPressed = useKeyPress(13)
    const escPressed = useKeyPress(27)
    let inputFocus = useRef(null)
    const { error } = config;
    const editFileName = (id, title, isNew) => {
        updateFIleName(id, title, isNew)
        setEditID(null)
    }
    useEffect(() => {
        if (enterPressed && (file.isNew || editID)) {
            if (inputFocus.current && inputFocus.current.state) {
                if (!inputFocus.current.state.value.trim()) {
                    error('文件名不能为空')
                    editFileName(file.id, file.title, file.isNew)
                    return;
                }
                editFileName(file.id, inputFocus.current.state.value, file.isNew)
            }
        }

        // 如果点击ESC键表示退出编辑状态
        if (escPressed && (file.isNew || editID)) {
            editFileName(file.id, file.title, file.isNew)
        }
        if (file.isNew || editID) {
            if (inputFocus.current) {
                inputFocus.current.focus();
            }
        }
    })
    return (
        <div
            className='fileItem'
            style={{
                paddingLeft: padding ? padding + basePadding : basePadding
            }}
            onClick={() => { onFileClick(file.id) }}
            data-id={file.id}
            data-title={file.title}
        >
            <div className='fileItem-icon-name'>
                <IconFont type='iconwenjian' className='fileItem-icon' />
                {
                    file.isNew || file.id === editID ?
                        <Input
                            ref={inputFocus}
                            placeholder="Basic usage"
                            className='fileItem-input'
                            onBlur={() => {
                                editFileName(file.id, file.title, file.isNew)
                            }}
                            defaultValue={file.title}
                        /> :
                        <p className='fileItem-name'>{file.title}</p>
                }
            </div>
        </div>
    )
}
